package org.darcy.youchat.library.emoji;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;

public class EmotionView {

    private ViewPager emotionPager;
    private LinearLayout pageNumberLayout;
    private EditText messageEditText;

    private int pageCount;

    private Context context;

    private IEmotionSelectedListener listener;

    public void attachEditText(EditText messageEditText) {
        this.messageEditText = messageEditText;
    }

    private EmoticonViewPagerAdapter pagerAdapter = new EmoticonViewPagerAdapter();

    private int categoryIndex;

    private boolean isDataInitialized = false;

    private List<StickerCategory> categoryDataList;

    private List<Integer> categoryPageNumberList;

    private int[] pagerIndexInfo = new int[2];

    public AdapterView.OnItemClickListener emojiListener;

    private AdapterView.OnItemClickListener stickerListener;


    public void showStickers(int index) {
        if (this.isDataInitialized && getPagerInfo(this.emotionPager.getCurrentItem()) != null && this.pagerIndexInfo[0] == index && this.pagerIndexInfo[1] == 0)
            return;
        this.categoryIndex = index;
        showStickerGridView();
    }

    public void showEmojis() {
        showEmojiGridView();
    }

    private int getCategoryPageCount(StickerCategory category) {
        if (category == null)
            return (int) Math.ceil((EmojiManager.getDisplayCount() / 27.0F));
        if (category.hasStickers()) {
            List<StickerItem> stickers = category.getStickers();
            return (int) Math.ceil((stickers.size() / 8.0F));
        }
        return 1;
    }

    private void setCurPage(int page, int pageCount) {
        int hasCount = this.pageNumberLayout.getChildCount();
        int forMax = Math.max(hasCount, pageCount);
        ImageView imgCur = null;
        int i = 0;
        while (true) {
            if (i < forMax) {
                if (pageCount <= hasCount) {
                    if (i >= pageCount) {
                        this.pageNumberLayout.getChildAt(i).setVisibility(View.GONE);
                    } else {
                        imgCur = (ImageView) this.pageNumberLayout.getChildAt(i);
                        imgCur.setId(i);
                    }
                } else {
                    if (i < hasCount) {
                        imgCur = (ImageView) this.pageNumberLayout.getChildAt(i);
                    } else {
                        imgCur = new ImageView(this.context);
                        imgCur.setBackgroundResource(R.drawable.nim_view_pager_indicator_selector);
                        this.pageNumberLayout.addView(imgCur);
                    }
                    imgCur.setId(i);
                }
            } else {
                break;
            }
            i++;
        }
    }

    private void showEmojiGridView() {
        this.pageCount = (int) Math.ceil((EmojiManager.getDisplayCount() / 27.0F));
        this.pagerAdapter.notifyDataSetChanged();
        resetEmotionPager();
    }

    private void resetEmotionPager() {
        setCurEmotionPage(0);
        this.emotionPager.setCurrentItem(0, false);
    }

    private void setCurEmotionPage(int position) {
        setCurPage(position, this.pageCount);
    }

    public EmotionView(Context context, IEmotionSelectedListener mlistener, ViewPager mCurPage, LinearLayout pageNumberLayout) {
        this.emojiListener = (arg0, arg1, arg2, arg3) -> {
            int position = EmotionView.this.emotionPager.getCurrentItem();
            int pos = position;
            if (EmotionView.this.categoryDataList != null && EmotionView.this.categoryPageNumberList != null) {
                EmotionView.this.getPagerInfo(position);
                pos = EmotionView.this.pagerIndexInfo[1];
            }
            int index = arg2 + pos * 27;
            if (EmotionView.this.listener != null) {
                int count = EmojiManager.getDisplayCount();
                if (arg2 == 27 || index >= count) {
                    EmotionView.this.listener.onEmojiSelected("/DEL");
                    EmotionView.this.onEmojiSelected("/DEL");
                } else {
                    String text = EmojiManager.getDisplayText((int) arg3);
                    if (!TextUtils.isEmpty(text)) {
                        EmotionView.this.listener.onEmojiSelected(text);
                        EmotionView.this.onEmojiSelected(text);
                    }
                }
            }
        };
        this.stickerListener = (arg0, arg1, arg2, arg3) -> {
            int position = EmotionView.this.emotionPager.getCurrentItem();
            EmotionView.this.getPagerInfo(position);
            int cIndex = EmotionView.this.pagerIndexInfo[0];
            int pos = EmotionView.this.pagerIndexInfo[1];
            StickerCategory c = EmotionView.this.categoryDataList.get(cIndex);
            int index = arg2 + pos * 8;
            if (index >= c.getStickers().size()) {
                Log.i("sticker", "index " + index + " larger than size " + c.getStickers().size());
                return;
            }
            if (EmotionView.this.listener != null) {
                StickerManager manager = StickerManager.getInstance();
                List<StickerItem> stickers = c.getStickers();
                StickerItem sticker = stickers.get(index);
                StickerCategory real = manager.getCategory(sticker.getCategory());
                if (real == null)
                    return;
                EmotionView.this.listener.onStickerSelected(sticker.getCategory(), sticker.getName(), StickerManager.getInstance().getStickerBitmapPath(sticker.getCategory(), sticker.getName()));
            }
        };
        this.context = context.getApplicationContext();
        this.listener = mlistener;
        this.pageNumberLayout = pageNumberLayout;
        this.emotionPager = mCurPage;
        this.emotionPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageSelected(int position) {
                if (EmotionView.this.categoryDataList != null) {
                    EmotionView.this.setCurStickerPage(position);
                } else {
                    EmotionView.this.setCurEmotionPage(position);
                }
            }
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            public void onPageScrollStateChanged(int state) {
            }
        });
        this.emotionPager.setAdapter(this.pagerAdapter);
        this.emotionPager.setOffscreenPageLimit(1);
    }

    private void onEmojiSelected(String key) {
        if (this.messageEditText == null) {
            return;
        }
        Editable mEditable = this.messageEditText.getText();
        if (key.equals("/DEL")) {
            this.messageEditText.dispatchKeyEvent(new KeyEvent(0, 67));
        } else {
            int start = this.messageEditText.getSelectionStart();
            int end = this.messageEditText.getSelectionEnd();
            start = (start < 0) ? 0 : start;
            mEditable.replace(start, end, key);
            int editEnd = this.messageEditText.getSelectionEnd();
            MoonUtils.replaceEmoticons(YouChatEmotionKit.getContext(), mEditable, 0, mEditable.toString().length());
            this.messageEditText.setSelection(editEnd);
        }
    }

    private void showStickerGridView() {
        initData();
        this.pagerAdapter.notifyDataSetChanged();
        int position = 0;
        for (int i = 0; i < this.categoryPageNumberList.size() && i != this.categoryIndex; i++)
            position += ((Integer) this.categoryPageNumberList.get(i)).intValue();
        setCurStickerPage(position);
        this.emotionPager.setCurrentItem(position, false);
    }

    private void initData() {
        if (this.isDataInitialized)
            return;
        if (this.categoryDataList == null)
            this.categoryDataList = new ArrayList<>();
        if (this.categoryPageNumberList == null)
            this.categoryPageNumberList = new ArrayList<>();
        this.categoryDataList.clear();
        this.categoryPageNumberList.clear();
        StickerManager manager = StickerManager.getInstance();
        this.categoryDataList.add(null);
        this.categoryPageNumberList.add(getCategoryPageCount(null));
        List<StickerCategory> categories = manager.getStickerCategories();
        this.categoryDataList.addAll(categories);
        for (StickerCategory c : categories)
            this.categoryPageNumberList.add(getCategoryPageCount(c));
        this.pageCount = 0;
        for (Integer count : this.categoryPageNumberList)
            this.pageCount += count.intValue();
        this.isDataInitialized = true;
    }

    private int[] getPagerInfo(int position) {
        if (this.categoryDataList == null || this.categoryPageNumberList == null)
            return this.pagerIndexInfo;
        int cIndex = this.categoryIndex;
        int startIndex = 0;
        int pageNumberPerCategory = 0;
        for (int i = 0; i < this.categoryPageNumberList.size(); i++) {
            pageNumberPerCategory = ((Integer) this.categoryPageNumberList.get(i)).intValue();
            if (position < startIndex + pageNumberPerCategory) {
                cIndex = i;
                break;
            }
            startIndex += pageNumberPerCategory;
        }
        this.pagerIndexInfo[0] = cIndex;
        this.pagerIndexInfo[1] = position - startIndex;
        return this.pagerIndexInfo;
    }

    private void setCurStickerPage(int position) {
        getPagerInfo(position);
        int categoryIndex = this.pagerIndexInfo[0];
        int pageIndexInCategory = this.pagerIndexInfo[1];
        int categoryPageCount = this.categoryPageNumberList.get(categoryIndex).intValue();
        setCurPage(pageIndexInCategory, categoryPageCount);
    }


    private class EmoticonViewPagerAdapter extends PagerAdapter {
        private EmoticonViewPagerAdapter() {
        }

        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        public int getCount() {
            return (EmotionView.this.pageCount == 0) ? 1 : EmotionView.this.pageCount;
        }

        public Object instantiateItem(ViewGroup container, int position) {
            StickerCategory category;
            int pos;
            if (EmotionView.this.categoryDataList != null && EmotionView.this.categoryDataList.size() > 0 && EmotionView.this.categoryPageNumberList != null && EmotionView.this
                    .categoryPageNumberList.size() > 0) {
                EmotionView.this.getPagerInfo(position);
                int cIndex = EmotionView.this.pagerIndexInfo[0];
                category = EmotionView.this.categoryDataList.get(cIndex);
                pos = EmotionView.this.pagerIndexInfo[1];
            } else {
                category = null;
                pos = position;
            }
            if (category == null) {
                RelativeLayout relativeLayout = new RelativeLayout(EmotionView.this.context);
                EmotionView.this.pageNumberLayout.setVisibility(View.VISIBLE);
                GridView gridView1 = new GridView(EmotionView.this.context);
                gridView1.setOnItemClickListener(EmotionView.this.emojiListener);
                gridView1.setAdapter(new EmojiAdapter(EmotionView.this.context, pos * 27));
                gridView1.setNumColumns(7);
                gridView1.setHorizontalSpacing(5);
                gridView1.setVerticalSpacing(5);
                gridView1.setGravity(17);
                gridView1.setSelector(R.drawable.nim_emoji_item_selector);
                relativeLayout.setGravity(17);
                relativeLayout.addView((View) gridView1);
                container.addView((View) relativeLayout);
                return relativeLayout;
            }
            RelativeLayout rl = new RelativeLayout(EmotionView.this.context);
            EmotionView.this.pageNumberLayout.setVisibility(View.VISIBLE);
            GridView gridView = new GridView(EmotionView.this.context);
            gridView.setPadding(10, 0, 10, 0);
            gridView.setOnItemClickListener(EmotionView.this.stickerListener);
            gridView.setAdapter(new StickerAdapter(EmotionView.this.context, category, pos * 8));
            gridView.setNumColumns(4);
            gridView.setHorizontalSpacing(5);
            gridView.setGravity(17);
            gridView.setSelector(R.drawable.nim_emoji_item_selector);
            rl.setGravity(17);
            rl.addView(gridView);
            container.addView(rl);
            return rl;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            View layout = (View) object;
            container.removeView(layout);
        }

        public int getItemPosition(Object object) {
            return -2;
        }
    }
}
